<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <el-button
          type="primary"
          class="button"
          :icon="Plus"
          @click="addTrademark"
        >
          添加
        </el-button>
      </div>
    </template>
    <el-table
      v-loading="loading"
      :data="trademarkList"
      border
      style="width: 100%"
    >
      <el-table-column type="index" label="序号" align="center" width="100%" />
      <el-table-column
        prop="tmName"
        label="品牌名称"
        align="center"
        width="300"
      />
      <el-table-column prop="" label="品牌LOGO" align="center" width="300">
        <template v-slot="{ row }">
          <img :src="row.logoUrl" alt="" style="width: 100px" />
        </template>
      </el-table-column>
      <el-table-column prop="address" align="center" label="操作">

        <template v-slot="{row}">
          <el-button type="warning" size="small" class="button" :icon="Edit" @click="editTrademark(row)"
          >编辑</el-button >
        <el-button type="success" size="small" class="button" :icon="Delete"
        @click="removeTrademark(row.id)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <el-pagination
      v-model:currentPage="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15, 20]"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager,next,-> , jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 对话框 -->
    <el-dialog v-model="outerVisible" :title="`${trademarkInfo.id?'编辑更新':'添加'}品牌`">
      <template #default>
        <el-form :model="trademarkInfo" ref="formRef" :rules="rules">
          <!-- <el-form-item
            
            label="品牌名称"
            :rules="[
              {
                required: true,
                message: '请输入品牌名',
                trigger: 'blur',
                min:1,
                max:6,
              },
              // {
              //   type: 'string',
              //   message: '请添加正确的品牌LOGO',
              //   trigger: ['blur', 'change'],
              // },
            ]"
          > -->
          <el-form-item label="品牌名称" prop="tmName" >
            <el-input v-model="trademarkInfo.tmName" autocomplete="off"/>
          </el-form-item>
          <!-- <el-form-item
           
            :label="'品牌LOGO'"
            :rules="{
              required: true,
              message: '选择要上传的LOGO照片',
              trigger: ['blur','change'],
            }"
          > -->
          <el-form-item label="品牌LOGO" label-width="90px" prop="logoUrl">
            <!-- <el-input v-model="domain.value"> -->
              <el-upload class="avatar-uploader" :action="`${BASE_URL}/admin/product/fileUpload`" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <!-- <img v-if="imageUrl" :src="imageUrl" class="avatar" /> -->
            <img v-if="trademarkInfo.logoUrl" :src="trademarkInfo.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
              <template #tip>
                <div class="el-upload__tip">
                  LOGO照片必须是 JPG,PNG,JPEG,GIF,WEBP 格式!
                </div>
              </template>
          </el-upload>

            <!-- <el-button class="mt-2" @click.prevent="removeDomain(domain)"
              >删除</el-button> -->
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm(formRef)"
              >提交</el-button
            >
            <!-- <el-button @click="addDomain">新增</el-button> -->
            <el-button @click="resetForm(formRef)">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- <el-dialog
          v-model="innerVisible"
          width="30%"
          title="添加成功"
          append-to-body
        /> -->
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="outerVisible = false">取消</el-button>
          <el-button type="primary" @click="primarySubmit"
            >确定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>
<script lang="ts">
//上传照片地址
const BASE_URL = import.meta.env.VITE_API_URL;
export default {
  name: "Trademark",
};
</script>
<!-- 表单 -->
<script lang="ts" setup>
import { Plus, Delete, Edit } from "@element-plus/icons-vue";
import { getTrademarkList,updateTrademarkList,saveTrademarkList,deleteTrademarkList } from "@/api/product/trademark";
import { onMounted, ref, reactive } from "vue";
// 引入类型约束的接口
import type { TrademarkListModel, TrademarkModel } from "@/api/product/model/trademark";
import { type FormInstance, type UploadProps,type FormRules, ElMessageBox } from "element-plus";
import { ElMessage } from "element-plus";
import { update } from "lodash";
//定义数据
// let page = ref(1);
// let limit = ref(5);
const trademarkList = ref<TrademarkListModel>([]);
const loading = ref(true);
let currentPage = ref(1); //当前页
const pageSize = ref(5); //每页显示默认值
const small = ref(false);
const background = ref(false);
const disabled = ref(false);
let total = ref(0); //品牌总量
let outerVisible = ref(false);
//内置dialog
// const innerVisible = ref(false);
const imageUrl = ref("");
const getTrademarkListData = async () => {
  const result = await getTrademarkList(currentPage.value, pageSize.value);
  console.log(result);
  trademarkList.value = result.records;
  total.value = result.total;
};
//将当前数据数组使用ref传递 .valueProxy数据格式
const initTrademark = ()=>({
  tmName:'',
  logoUrl:''
})
const trademarkInfo=reactive<TrademarkModel>(
  initTrademark()  
)
onMounted(() => {
  //重新获取请求
  getTrademarkListData();
  loading.value = false;
});

//当前页显示多少条
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  pageSize.value = val;
  currentPage.value = 1;
  getTrademarkListData();
};
//当前页
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  currentPage.value = val;
  getTrademarkListData();
};
//添加品牌时显示对话框 清空原来的数据
const addTrademark = () => {
  outerVisible.value = true;
  Object.assign(trademarkInfo,initTrademark())
  delete trademarkInfo.id;
  formRef.value?.clearValidate()
};

//
const formRef = ref<FormInstance>();
  
// const dynamicValidateForm = reactive<{
//   domains: DomainItem[];
//   email: string;
// }>({
//   domains: [
//     {
//       key: 1,
//       value: "",
//     },
//   ],
//   email: "",
// });

// interface DomainItem {
//   key: number;
//   value: string;
// }
//删除
// const removeDomain = (item: DomainItem) => {
//   const index = dynamicValidateForm.domains.indexOf(item);
//   if (index !== -1) {
//     dynamicValidateForm.domains.splice(index, 1);
//   }
// };
//新增
// const addDomain = () => {
//   dynamicValidateForm.domains.push({
//     key: Date.now(),
//     value: "",
//   });
// };
//提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate( async (valid,fields) => {
    console.log('form',valid,fields);
    
    if (valid) {
      console.log("submit!");
      if(trademarkInfo.id) {
        await updateTrademarkList(trademarkInfo);
        ElMessage.success('品牌修改成功')
      }else{
        await saveTrademarkList(trademarkInfo);
        ElMessage({
          type:'success',
          message:'品牌增加成功'
        });
        currentPage.value = total.value/pageSize.value
      }
    } else {
      console.log("error submit!");
      return false;
    }
  });
};
//重置
const resetForm = (formEl: FormInstance | undefined) => {
  outerVisible.value = true;
  Object.assign(trademarkInfo,initTrademark())
  delete trademarkInfo.id;
  formRef.value?.clearValidate()
  if (!formEl) return;
  formEl.resetFields();
};
//添加LOGO图片

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  trademarkInfo.logoUrl = response.data;
  //清楚之前的图片校验规则
  formRef.value?.clearValidate(['logoUrl'])
};
//校验规则
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: '请添加品牌名称', trigger: 'blur' },
    { min: 1, max: 6, message: '长度在1到6之间', trigger: 'blur' }
  ],
  logoUrl: [{ required: true, message: '请选择要上传的图片', trigger: 'change' }]
})
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const imgArr = ['image/jpeg','image/png','image/jpg','image/jif','image/webp',]
  // if (!imgArr.includes(rawFile.type)) {
    if(!trademarkInfo){
    ElMessage.error("LOGO照片必须是 JPG,PNG,JPEG,GIF,WEBP 格式!");
    return false;
  } else if (rawFile.size / 1024 / 1024>2 ) {
    ElMessage.error("LOGO照片大小不能超过2MB!");
    return false;
  }
  return true;
};
//点击确定后重新请求数据
const primarySubmit = ()=>{
  outerVisible.value = false
  getTrademarkListData();
}
//点击编辑 品牌数据回显
const editTrademark = (row:TrademarkModel)=>{
  //弹框显示
  outerVisible.value = true;
  //弹框显示所点击的数据
  Object.assign(trademarkInfo,row)
  getTrademarkListData();
}
//点击删除 根据id删除
const removeTrademark = (id:number)=>{
  ElMessageBox.confirm('您确定要删除此品牌???','提示',{
    confirmButtonText:'确定',
    cancelButtonText:'取消',
    type:'warning'
  })
  .then(async ()=>{
    await deleteTrademarkList(id);
    ElMessage({
      type:'success',
      message:'成功删除此品牌'
    });
    getTrademarkListData();
  } )
  .catch(()=>{
    ElMessage({
      type:'info',
      message:'取消删除...'
    })
  })
  
}
</script>
<style>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.el-upload__tip{
  color:rgb(244, 10, 10)
}
</style>
